package cn.wolfcode.exception;

import cn.wolfcode.qo.JsonResult;
import com.alibaba.fastjson.JSON;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.HandlerMethod;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@ControllerAdvice//对控制器增强捕捉异常
public class HandlerControllerException {
    /**
     * 对控制器进行增强处理
     */


        //ExceptionHandler代表当前的方法时处理异常,处理什么异常
        //HandlerMethod 代表出现异常的处理方法
        @ExceptionHandler(RuntimeException.class)
        public Object handleException(RuntimeException e, HandlerMethod method, HttpServletResponse response) {
            //把异常信息打印出,方便我们开发的时候找bug
            e.printStackTrace();
            //判断有没有贴ResponseBody注解
            if (method.hasMethodAnnotation(ResponseBody.class)) {
                //如果是,则返回jsonresult
                String errorMsg = "操作失败,请联系管理员!";
                //判断是否逻辑异常,如果是,直接用自己的异常错误信息
                if (e instanceof LogincException){
                    errorMsg = e.getMessage();
                }

                JsonResult json = new JsonResult(false, errorMsg);
                //使用response对象输出数据(json字符串)
                response.setContentType("application/json;charset=utf-8");
                try {
                    // 返回错误信息
                    response.getWriter().print(JSON.toJSONString(json));
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
                return null;
            }else {
                //如果不是,则返回错误视图
                return "common/error";
            }
        }


    /**
     * 捕获没有授权的异常
     * @param e
     * @param response
     * @param method
     * @return
     */
    @ExceptionHandler(UnauthorizedException.class)
    public Object handlerException1(UnauthorizedException e, HttpServletResponse response, HandlerMethod method) {
        e.printStackTrace(); //方便找到bug
        //判断有没有贴ResponseBody注解
        if (method.hasMethodAnnotation(ResponseBody.class)){
            String errorMsg = "你没有权限操作";
            JsonResult jsonResult = new JsonResult(false,errorMsg);
            response.setContentType("application/json;charset=utf-8");
            try {
                response.getWriter().print(JSON.toJSONString(jsonResult));
            } catch (IOException e1) {
                e1.printStackTrace();
            }
            return null;
        }else {
            return "common/nopermission";
        }

    }
    }

